#include "stdafx.h"
#include "ckRasterImpl.h"
#include "ckRasterBandImpl.h"

namespace ck
{
	namespace data
	{
		RasterImpl::RasterImpl()
		{
			m_poDataset = NULL;
		}

		RasterImpl::~RasterImpl()
		{
			Close();
		}

		void RasterImpl::SetPath(const char* szPath)
		{
			if (szPath==NULL)
			{
				m_strPath.clear();
			}
			else
			{
				m_strPath = szPath;
			}
		}

		RESULTCODE RasterImpl::Open()
		{
			if (m_poDataset)
			{
				return RC_SUCCESS;
			}

			m_poDataset = (GDALDataset*)GDALOpen(m_strPath.c_str(), GA_ReadOnly);
			if (m_poDataset == NULL)
			{
				return RC_FAILURE;
			}

			int nBand = m_poDataset->GetRasterCount();
			m_bands.resize(nBand);
			for (int i = 0; i < nBand; i++)
			{
				m_bands[i] = NULL;
			}


			return RC_SUCCESS;
		}

		bool RasterImpl::IsOpen()
		{
			return (m_poDataset!=NULL);
		}

		void RasterImpl::Close()
		{
			Cleanup();
			if (m_poDataset)
			{
				GDALClose(m_poDataset);
				m_poDataset = NULL;
			}
		}

		z_uint32 RasterImpl::GetBandCount()
		{
			if (!m_poDataset)
			{
				return 0;
			}
			return m_poDataset->GetRasterCount();
		}

		RasterBand*	RasterImpl::GetBand(z_uint32 i)
		{
			if (!m_poDataset)
			{
				return NULL;
			}

			int nBand = m_poDataset->GetRasterCount();
			if (i >= nBand)
			{
				return NULL;
			}

			RasterBand* pBand = m_bands[i];
			if (pBand != NULL)
			{
				return pBand;
			}

			GDALRasterBand* poBand = m_poDataset->GetRasterBand(i + 1);
			if (poBand == NULL)
			{
				return NULL;
			}

			RasterBandImpl* pBandImpl = new RasterBandImpl(poBand);
			m_bands[i] = pBandImpl;
			
			return pBandImpl;
		}

		void RasterImpl::Cleanup()
		{
			RasterBand* pBand = NULL;
			std::vector<data::RasterBand*>::iterator iter;
			for (iter = m_bands.begin(); iter != m_bands.end(); iter++)
			{
				pBand = *iter;
				if (pBand)
				{
					pBand->Release();
					(*iter) = NULL;
				}
			}
		}
	}
}
